package menu

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"fmt"
	"google.golang.org/grpc/codes"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserGetMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserGetMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserGetMenuLogic {
	return &UserGetMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserGetMenuLogic) UserGetMenu(req *types.UserMenuReq) (*types.MenuRsp, error) {

	var resp types.MenuRsp

	// 查询专栏详情，只查询已发布的专栏
	if err := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityMenu{}).
		Joins("menu").
		Joins(fmt.Sprintf("LEFT JOIN %s topic ON topic.menu_id = menu.id", model.TableNameCsCommunityTopic)).
		Where("menu.id = ? AND menu.publish = ?", req.Id, types.MenuStatusPublish).
		Select("menu.*", "COUNT(topic.id) topic_count").Group("menu.id").
		Find(&resp).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if resp.Id == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.MenuNotFound)
	}

	// 查询该专栏下的所有topics，包含统计信息
	topicQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityTopic{}).
		Joins("topic").
		Joins("LEFT JOIN cs_community_post post ON post.topic_id = topic.id").
		Select(
			"topic.id", "topic.name", "topic.image_url", "topic.description",
			"topic.menu_id", "topic.type", fmt.Sprintf("CASE WHEN topic.type = %d THEN 1 END disabled", types.TopicTypeForbidden),
			"IFNULL(COUNT(DISTINCT post.id), 0) as post_count",
			"IFNULL(SUM(post.view_count), 0) as view_count",
		).
		Where("topic.menu_id = ?", req.Id).
		Group("topic.id").
		Order("topic.id ASC")

	if err := topicQuery.Find(&resp.Topics).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &resp, nil
}
